import nodemailer from "nodemailer";

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ message: "只支持 POST" });
  }

  const data = req.body;
  console.log("收到位置：", data);

  try {
    const transporter = nodemailer.createTransport({
      service: 'qq',
      auth: {
        user: process.env.EMAIL_USER,  // 邮箱账号
        pass: process.env.EMAIL_PASS,  // 邮箱授权码
      },
    });

    const mailOptions = {
      from: '"位置共享通知" <' + process.env.EMAIL_USER + '>',
      to: process.env.EMAIL_RECEIVE,   // 接收通知邮箱
      subject: '紧急位置上报',
      text: `有人提交了位置：
经度：${data.longitude}
纬度：${data.latitude}
精度：${data.accuracy} 米
时间：${data.timestamp}`,
    };

    await transporter.sendMail(mailOptions);

    res.status(200).json({ message: "位置已收到并发送邮件", data });
  } catch (error) {
    console.error("发送邮件失败：", error);
    res.status(500).json({ message: "位置收到，但邮件发送失败", error });
  }
}
